define(['jquery', 'bootstrap', 'backend', 'table', 'form'], function ($, undefined, Backend, Table, Form) {

    var Controller = {
        index: function () {
            // 初始化表格参数配置
            Table.api.init({
                extend: {
                    index_url: 'speech/speech/index',
                    add_url: 'speech/speech/add',
                    edit_url: 'speech/speech/edit',
                    del_url: 'speech/speech/del',
                    multi_url: 'speech/speech/multi',
                    table: 'speech',
                }
            });
            var table = $("#table");
            // 初始化表格
            table.bootstrapTable({
                url: $.fn.bootstrapTable.defaults.extend.index_url,
                pk: 'id',
                sortName: 'id',
                pageSize: 20,
                pageList: [20, 50],
                clickToSelect: false,
                dblClickToEdit: false,
                singleSelect: false,
                columns: [
                    [{
                            checkbox: true
                        },
                        {
                            field: 'id',
                            title: __('Id')
                        },
                        {
                            field: 'name',
                            title: __('Name')
                        },
                        // {field: 'admin_id', title: __('Admin_id'), visible: false},
                        // {
                        //     field: 'industry',
                        //     title: __('Industry'),
                        //     visible: false,
                        //     searchList: {
                        //         "finance": __('industry finance'),
                        //         "house": __('industry house'),
                        //         "edu": __('industry edu'),
                        //         "ad": __('industry ad'),
                        //         "other": __('industry other')
                        //     }
                        // },
                        {
                            field: 'industry_text',
                            title: __('Industry')
                        },
                        {
                            field: 'admin.nickname',
                            title: __('创建人')
                        },
                        // {field: 'speech.name', title: __('话术名称')},
                        {
                            field: 'createtime',
                            title: __('Createtime'),
                            operate: 'RANGE',
                            addclass: 'datetimerange',
                            formatter: Table.api.formatter.datetime
                        },
                        // {
                        //     field: 'updatetime',
                        //     title: __('Updatetime'),
                        //     operate: 'RANGE',
                        //     addclass: 'datetimerange',
                        //     visible: false,
                        //     formatter: Table.api.formatter.datetime
                        // },
                        {
                            field: 'id',
                            title: __('配置话术路径'),
                            operate: false,
                            formatter: Controller.api.formatter.id
                        },
                        {
                            field: 'id',
                            title: __('配置话术关键词'),
                            operate: false,
                            formatter: Controller.api.formatter.speech_id
                        },
                        {
                            field: 'id',
                            title: __('配置话术评级'),
                            operate: false,
                            formatter: Controller.api.formatter.grade
                        },
                        // {
                        //     field: 'admin.id',
                        //     title: __('Admin.id'),
                        //     visible: false
                        // },
                        {
                            field: 'operate',
                            width: "120px",
                            title: __('Operate'),
                            table: table,
                            buttons: [{
                                name: 'detail',
                                title: __('试听'),
                                icon: 'fa fa-phone',
                                 classname: 'btn-td btn-phone'
                                // classname: 'btn-td btn-phone btn-dialog'
                                // ,
                                // extend: 'data-toggle="tooltip"',
                                // url: 'speech/speech/detail'
                            }],
                            events: Table.api.events.operate,
                            formatter: Table.api.formatter.operate
                        }
                        // {
                        //     field: 'operate',
                        //     title: __('Operate'),
                        //     table: table,
                        //     buttons: [
                        //         {
                        //             name: "router",
                        //             icon: 'fa fa-list',
                        //             title: __('话术路径'),
                        //             extend: 'data-toggle="tooltip"',
                        //             classname: 'btn btn-xs btn-primary btn-speech-route'
                        //         }
                        //     ],
                        //     events: {
                        //         'click .btn-speech-route': function (e, value, row, index) {
                        //             e.stopPropagation();
                        //             e.preventDefault();
                        //             var table = $(this).closest('table');
                        //             var options = table.bootstrapTable('getOptions');
                        //             var ids = row[options.pk];
                        //             row = $.extend({}, row ? row : {}, {ids: ids});
                        //             var url = '';
                        //             //url = Table.api.replaceurl(url, row, table);
                        //             //url = Fast.api.fixurl(url);
                        //             url = 'speech/router?speech_id=' + row.id;
                        //             //location.href = '../' + url;
                        //             Backend.api.addtabs(url, __('话术路径') + '&nbsp;-&nbsp;' + row.name, 'fa fa-list-alt');
                        //             //Fast.api.open(Table.api.replaceurl(url, row, table), __('话术路径'), $(this).data() || {});
                        //
                        //         }
                        //     },
                        //     formatter: Table.api.formatter.operate
                        //     // formatter: Controller.api.formatter.id
                        // }
                    ]
                ]
            });
            // $(document).on("click", '.btn-phone',function(e) {
            //     var phoneId=$(this).parent().parent().find('td').eq(1).text();
            //     // $('#phone_num').val('AIScript-'+phoneId+'');
            //     SIPClient.call(phoneId)
            // });
            // 为表格绑定事件
            Table.api.bindevent(table);
            require(['webrtc-adapter', 'sip-js', 'sip-client'], function(adapter, SIP, SIPClient) {
                SIPClient.init(SIP, extension_cfg);
                window.SIPClient = SIPClient;
            });
        },
        add: function () {
            Controller.api.bindevent();
        },
        edit: function () {
            Controller.api.bindevent();
        },
        detail: function () {
            $('.layui-layer-close1').addClass('detail-close');
            var data="{\"version\":\"1.0\",\"finished\":true,\"starttime\":1540174748,\"endtime\":1540174818,\"flow_result\":[{\"type\":\"robot\",\"voice\":{\"hint\":\"甘肃搜狗-您好\",\"path\":\"\\\/usr\\\/share\\\/nginx\\\/html\\\/public\\\/uploads\\\/20180809\\\/0984f422f58fae3fec6228ab6afdb147.wav\",\"time\":1540174748},\"flow_name\":\"您好\"},{\"type\":\"human\",\"voice\":{\"hint\":\"你好\",\"time\":1540174751},\"flow_name\":\"您好\"},{\"type\":\"robot\",\"voice\":{\"hint\":\"甘肃搜狗-开场白\",\"path\":\"\\\/usr\\\/share\\\/nginx\\\/html\\\/public\\\/uploads\\\/20180809\\\/1870263107044236c4e0f6f1d33da8f2.wav\",\"time\":1540174751},\"flow_name\":\"开场白\"},{\"type\":\"human\",\"voice\":{\"hint\":\"啊你好\",\"time\":1540174753},\"flow_name\":\"开场白\"},{\"type\":\"human\",\"voice\":{\"hint\":\"不需要\",\"time\":1540174762},\"flow_name\":\"开场白\"},{\"type\":\"robot\",\"voice\":{\"hint\":\"甘肃搜狗-关键词-目前没考虑\",\"path\":\"\\\/usr\\\/share\\\/nginx\\\/html\\\/public\\\/uploads\\\/20180809\\\/4e1115504fe8cae76ff1636248e719f3.wav\",\"time\":1540174762},\"flow_name\":\"开场白_negative\"},{\"type\":\"robot\",\"voice\":{\"hint\":\"甘肃搜狗-公司介绍\",\"path\":\"\\\/usr\\\/share\\\/nginx\\\/html\\\/public\\\/uploads\\\/20180809\\\/e53c5bfdaf72ad8a51c20b8c6a6408f9.wav\",\"time\":1540174785},\"flow_name\":\"产品介绍\"},{\"type\":\"robot\",\"voice\":{\"hint\":\"甘肃搜狗-安排经理\",\"path\":\"\\\/usr\\\/share\\\/nginx\\\/html\\\/public\\\/uploads\\\/20180809\\\/e99759af0b3df57791a8f510f8043a01.wav\",\"time\":1540174802},\"flow_name\":\"安排经理\"},{\"type\":\"robot\",\"voice\":{\"hint\":\"静音检测\",\"path\":\"\\\/usr\\\/share\\\/nginx\\\/html\\\/public\\\/uploads\\\/20180926\\\/92a2e6aa82f08c8cedd7fd4441ffb5e1.wav\",\"time\":1540174811},\"flow_name\":\"安排经理\"}]}";
            var data_arr = eval("(" + data + ")").flow_result;
            for (var i = 0; i < data_arr.length; i++) {
                var date_value = timestampToTime(data_arr[i].voice.time);
                if (data_arr[i].type == "robot") {
                    if (data_arr[i].voice.hint ==null) {
                        data_arr[i].voice.hint="机器人合成语音";
                    }

                    if (data_arr[i].voice.path === undefined){
                        $('.qa-text').append("<li class='human'><span>" + date_value + "</span><div><p><span>机器人合成语音：" + data_arr[i].voice.hint + "</span></p></div><img src='/assets/img/jiqiren.png'/></li>");
                    }else{
                        $('.qa-text').append("<li class='human'><span>" + date_value + "</span><div><audio src='" + data_arr[i].voice.path.split("public")[1]+ "' style='display: none;'></audio><img src='/assets/img/bofang.png' class='audios'/><p><span>话术名称：" + data_arr[i].voice.hint + "</span></p></div><img src='/assets/img/jiqiren.png'/></li>");
                    }

                } else if (data_arr[i].type == "human") {
                    $('.qa-text').append("<li class='robot'><img src='/assets/img/tx1.png'/><div><p><span>客户：" + data_arr[i].voice.hint + "<br></span>命中关键词：<span>" + date_value + "</span></p></div><span>" + date_value + "</span></li>");
                }
            }
            $('.audios').on('click', function () {
                var pre = this.parentNode.getElementsByTagName('audio')[0];
                pre.pause();
                pre.currentTime = 0;
                if ($(this).attr('src') == "/assets/img/bofang.png") {
                    pre.play();
                    $('.audios').attr('src', '/assets/img/bofang.png');
                    $(this).attr('src', '/assets/img/zanting.png');
                } else {
                    pre.pause();
                    $(this).attr('src', '/assets/img/bofang.png');
                }
            })
            $('audio').on('ended', function () {
                $('.audios').attr('src', '/assets/img/bofang.png');
            });
            [].forEach.call(audios, function (i) {
                i.addEventListener("play", pauseAll.bind(i));
            })
            function timestampToTime(timestamp) {
                var date = new Date(timestamp * 1000);
                Y = date.getFullYear() + '-';
                M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '-';
                D = date.getDate() + ' ';
                if (date.getHours() < 10) {
                    h = '0' + date.getHours() + ':';
                } else {
                    h = date.getHours() + ':';
                }
                if (date.getMinutes() < 10) {
                    m = '0' + date.getMinutes() + ':';
                } else {
                    m = date.getMinutes() + ':';
                }
                if (date.getSeconds() < 10) {
                    s = '0' + date.getSeconds();
                } else {
                    s = date.getSeconds();
                }
                return Y + M + D + h + m + s;
            }
            
        },
        api: {
            bindevent: function () {
                Form.api.bindevent($("form[role=form]"));
            },
            formatter: {
                id: function (value, row, index) {
                    //这里手动构造URL
                    url = "speech/router?speech_id=" + value;

                    //方式一,直接返回class带有addtabsit的链接,这可以方便自定义显示内容
                    return '<a href="' + url + '" class="label label-info addtabsit" title="' + __("配置话术路径", value) + '">' + __('配置话术路径', value) + '</a>';

                    //方式二,直接调用Table.api.formatter.addtabs
                    //return Table.api.formatter.addtabs(value, row, index, url);
                },
                speech_id: function (value, row, index) {
                    //这里手动构造URL
                    url = "speech/faq?speech_id=" + value;

                    //方式一,直接返回class带有addtabsit的链接,这可以方便自定义显示内容
                    return '<a href="' + url + '" class="label label-info addtabsit" title="' + __("配置话术关键词", value) + '">' + __('配置话术关键词', value) + '</a>';

                    //方式二,直接调用Table.api.formatter.addtabs
                    //return Table.api.formatter.addtabs(value, row, index, url);
                },
                grade: function (value, row, index) {
                    //这里手动构造URL
                    url = "speech/grade?speech_id=" + value;

                    //方式一,直接返回class带有addtabsit的链接,这可以方便自定义显示内容
                    return '<a href="' + url + '" class="label label-info addtabsit" title="' + __("配置话术评级", value) + '">' + __('配置话术评级', value) + '</a>';

                    //方式二,直接调用Table.api.formatter.addtabs
                    //return Table.api.formatter.addtabs(value, row, index, url);
                }
            }
        }
    };
    return Controller;
});